<template>
  <a-drawer
    :title="title"
    :width="drawerWidth"
    @close="handleCancel"
    :visible="visible"
    :confirmLoading="confirmLoading">

    <div :style="{width: '100%',border: '1px solid #e9e9e9',padding: '10px 16px',background: '#fff',}">
      <a-spin :spinning="confirmLoading">
        <a-form :form="form">
          <a-form-item label="菜单类型" :labelCol="labelCol" :wrapperCol="wrapperCol" >
            <a-radio-group @change="onChangeMenuType" v-decorator="['menuType',{'initialValue':localMenuType}]">
              <a-radio :value="0">模块</a-radio>
              <a-radio :value="2">权限</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :label="menuLabel"
            hasFeedback >
            <a-input placeholder="请输入模块名称" v-decorator="[ 'name', validatorRules.name]" :readOnly="disableSubmit"/>
          </a-form-item>

          <a-form-item
            label="上级模块"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :validate-status="validateStatus"
            :required="requiredFlag"
            :hasFeedback="true">
            <span slot="help">{{ validateStatus=='error'?'请选择上级模块':'&nbsp;&nbsp;' }}</span>
            <a-tree-select
              style="width:100%"
              :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
              :treeData="treeData"
              v-model="model.parentId"
              placeholder="请选择父级模块"
              :disabled="disableSubmit">
            </a-tree-select>
          </a-form-item>
          <a-form-item
            v-show="!show"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="授权标识">
            <a-input placeholder="请输入授权标识, 如: user:list" v-decorator="[ 'perms', {rules:[{ required: false, message: '请输入授权标识!' }, { max: 50, message: '不能超过50个字符' },{validator: this.validatePerms }]}]" :readOnly="disableSubmit"/>
          </a-form-item>
          <a-form-item
            v-show="show"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="排序">
            <a-input placeholder="请输入菜单排序" style="width: 200px" v-decorator="[ 'sortNo',validatorRules.sortNo]" :readOnly="disableSubmit"/>
          </a-form-item>
        </a-form>
      </a-spin>
      <a-row :style="{textAlign:'right'}">
        <a-button :style="{marginRight: '8px'}" @click="handleCancel">
          关闭
        </a-button>
        <a-button :disabled="disableSubmit" @click="handleOk" type="primary">确定</a-button>
      </a-row>
    </div>
  </a-drawer>
</template>

<script>
  import { addPermission, editPermission, queryTreeList } from '../service'
  import { duplicateCheck } from '@/api/api.js'
  import Icons from '@/assets/menuIcon/Icons.vue'
  import pick from 'lodash.pick'

  export default {
    name: 'AuthorityModal',
    components: { Icons },
    data () {
      return {
        drawerWidth: 700,
        treeData: [],
        title: '操作',
        visible: false,
        disableSubmit: false,
        model: {},
        localMenuType: 0,
        show: true, // 根据菜单类型，动态显示隐藏表单元素
        requiredFlag: false,
        component: 'layouts/RouteView', // 组件默认值
        url: '',
        menuLabel: '模块名称',
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },

        confirmLoading: false,
        form: this.$form.createForm(this),
        validateStatus: '',
        appId: ''
      }
    },
    computed: {
      validatorRules: function() {
        return {
          name: { rules: [{ required: true, message: '请输入模块标题!' }, { max: 50, message: '不能超过50个字符' }] },
          sortNo: { rules: [{ pattern: /^[1-9]\d{0,7}$/, message: '输入不超过8位数的正整数' }] }
        }
      }
    },
    created () {
      this.initDictConfig();
    },
    methods: {
      loadTree(appId) {
        var that = this;
        queryTreeList(appId, { type: 1 }).then((res) => {
          if (res.success) {
            console.log(res)
            that.treeData = [];
            let treeList = res.result.treeList
            for (let a = 0; a < treeList.length; a++) {
              let temp = treeList[a];
              temp.isLeaf = temp.leaf;
              that.treeData.push(temp);
            }
          }
        });
      },
      add (sysId) {
         this.appId = sysId;
        // 默认值
        this.edit({ status: '1', permsType: '1', route: true });
      },
      edit (record) {
        this.resetScreenSize(); // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度
        this.form.resetFields();
        this.model = Object.assign({}, record);
        if (record.appId) {
          this.model.appId = record.appId
        } else {
          this.model.appId = this.appId
        }
        this.show = record.menuType !== 2;
        this.requiredFlag = record.menuType === 2;
        if (record.menuType !== 2) {
          this.model.menuType = 0;
        }
        console.log(record)

        this.menuLabel = record.menuType === 2 ? '权限' : '模块名称';
        this.visible = true;
        this.loadTree(this.model.appId);
        let fieldsVal = pick(this.model, 'name', 'perms', 'menuType');
        this.$nextTick(() => {
          this.form.setFieldsValue(fieldsVal)
        });
      },
      close () {
        this.$emit('close');
        this.disableSubmit = false;
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            let formData = Object.assign(this.model, values);
            formData.leaf = 0;
            formData.component = this.component;
            formData.url = this.url;
            if (formData.menuType === 2 && (formData.parentId === undefined || formData.parentId === null || formData.parentId === '')) {
              that.validateStatus = 'error';
              that.$message.error('请检查你填的类型以及信息是否正确！');
              return;
            } else {
              that.validateStatus = 'success';
            }
            if (formData.menuType === 0 && formData.parentId > 0) {
              formData.menuType = 1;
            }
            if (formData.menuType === 2) {
              formData.leaf = 1;
            }
            that.confirmLoading = true;
            console.log(formData);
            let obj;
            if (!this.model.id) {
              obj = addPermission(formData);
            } else {
              obj = editPermission(formData);
            }
            obj.then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            });
          }
        })
      },
      handleCancel () {
        this.close()
      },
      validateNumber(rule, value, callback) {
        if (!value || new RegExp(/^[0-9]*[1-9][0-9]*$/).test(value)) {
          callback();
        } else {
          callback('请输入正整数!');
        }
      },
      validatePerms(rule, value, callback) {
        if (value && value.length > 0) {
          // 校验授权标识是否存在
          var params = {
            tableName: 'sys_permission',
            fieldName: 'perms',
            fieldVal: value,
            dataId: this.model.id
          };
          duplicateCheck(params).then((res) => {
            if (res.success) {
              callback()
            } else {
              callback('授权标识已存在!')
            }
          })
        } else {
          callback()
        }
      },
      onChangeMenuType(e) {
        if (e.target.value === 2) {
          this.menuLabel = '权限';
          this.show = false;
          this.requiredFlag = true;
        } else {
          this.menuLabel = '模块名称';
          this.show = true;
          this.requiredFlag = false;
        }
      },
      // 根据屏幕变化,设置抽屉尺寸
      resetScreenSize() {
        let screenWidth = document.body.clientWidth;
        if (screenWidth < 500) {
          this.drawerWidth = screenWidth;
        } else {
          this.drawerWidth = 700;
        }
      },
      initDictConfig() {
      }
    }
  }
</script>

<style scoped>

</style>
